/**
 * User: yeqingzhou01
 * Date: 13-9-30
 * Time: 下午3:52
 */
var util = require('util');
var errors = require('../error/errors');
var retObj = require('./ret-obj');

/**
 * Forwarding requests
 * @param businessType      i.e. job, business
 * @param operationType     i.e. get, post, put, delete
 * @param subject           i.e. data-meta, job-meta
 * @param functionName
 * @param argsArr           arguments of target function
 */
exports.requestRouteService = function (businessType, operationType, subject, functionName, argsArr, callback) {
    operationType = operationType.toLowerCase();
    var subjectBusiness = require(
        './'
            + subject + '-'
            + businessType
    );
    var dealWithException = function (errorObj, callback) {
        util.log('[ERROR] ' + errorObj.message);
        callback(
            retObj.getOrdinaryReturnObject(
                false,
                errorObj.message
            )
        );
    }
    try {
        subjectBusiness[operationType][functionName](
            argsArr,
            function (retData) {
                if (retData instanceof Error) {
                    dealWithException(retData, callback);
                } else if (typeof(retData) == 'object') {
                    callback(
                        retObj.getReturnObject(
                            true,
                            'ok',
                            retData
                        )
                    );
                } else if (typeof(retData) == 'string') {
                    callback(
                        retData
                    );
                } else {
                    callback(
                        retObj.getOrdinaryReturnObject(
                            true,
                            'ok'
                        )
                    );
                }
            }
        );
    } catch (e) {
        dealWithException(e, callback);
    }
}